﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Torch.WL.Business;
using Torch.WL.Business.Interface;
using Torch.FrameWork.Utility;
using Torch.FrameWork.Common;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.IO;
using System.Text;

namespace Torch.WL.Web.CleanChina
{
    public class data : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            DateTime begintime = DateTime.Now;
            context.Response.ContentType = "text/plain";
            MessageCodeType msgType;
            string inparameter = string.Empty;
            IDataProvider dataprovider = CreateProvider(context, out msgType, out inparameter);
            
            if (dataprovider != null)
            {
                try
                {
                    IMessageInfo message = dataprovider.Do();
                    context.Response.Write(JsonHelper.ToJson(message));

                    LogEvent.LogInfo("传入参数:"+inparameter +"||耗时:"+(DateTime.Now - begintime).Milliseconds.ToString() +"毫秒");
                }
                catch (Exception ex)
                {
                    LogEvent.LogError("发生异常,参数信息:"+inparameter+"||耗时:"+(DateTime.Now - begintime).Milliseconds.ToString() +"毫秒",ex);
                    msgType = MessageCodeType.Fail;
                    ResponseExceptionMsg(context, msgType);
                }
            }
            else
            {
                ResponseExceptionMsg(context, msgType);                
            }
        }

        void ResponseExceptionMsg(HttpContext context, MessageCodeType msgType)
        {
            IMessageInfo message = new MessageInfo();
            message.code = (int)msgType;
            message.message = Utils.GetEnumDescription(msgType);             
            message.data = null;
            context.Response.Write(JsonHelper.ToJson(message)); 
        }

        bool  GetPostParameter(HttpContext context, out string postdata)
        {
            postdata = string.Empty;
            if ("POST" == context.Request.RequestType)
            {
                try
                {
                    System.IO.Stream sm = context.Request.InputStream;//获取post正文
                    int len = (int)sm.Length;//post数据长度
                    byte[] inputByts = new byte[len];//字节数据,用于存储post数据
                    sm.Read(inputByts, 0, len);//将post数据写入byte数组中
                    sm.Close();//关闭IO流

                    postdata = Encoding.UTF8.GetString(inputByts);//转为UTF8编码
                    //data = Server.UrlDecode(data);//下面解释一下Server.UrlDecode和Server.UrlEncode的作用
                }
                catch (Exception ex)
                {
                    LogEvent.LogError("获取Postbody失败",ex);
                    return false;
                }

                return true;
            }

            return false;

        }
                
        private IDataProvider CreateProvider(HttpContext context,out MessageCodeType msgType , out string inparameter)
        {
            msgType = MessageCodeType.Success;
            inparameter = string.Empty;

            string postbody=string.Empty;
            string function = context.Request["function"];
            string identication = context.Request["identication"];
            string data = context.Request["data"];

            string json = "{identication:" + identication + ",data:" + data + "}";

            if (string.IsNullOrEmpty(identication) && string.IsNullOrEmpty(data))
            {
                if (GetPostParameter(context, out postbody))
                {
                    json = postbody;
                    LogEvent.LogInfo("postbody的值为=" + postbody);
                }
                else
                {
                    msgType = MessageCodeType.WrongRequestPara;
                    return null;
                }
            }
            else
            {
 
            }

            inparameter ="{\"function\":\"" +function +"\",\"params\":" +  json +"}";

            try
            {
                //string type = VerifyInfo<int>.GetIdenticationType(json);

                switch (function.ToLower())
                {
                    #region cases

                    case "basic":
                        return new LoginProvider(json);
                    case "expo":
                        return new ExpoInfoProvider(json);
                    case "expo1":
                        return new ExpoInfo1Provider(json);
                    case "expo2":
                        return new ExpoInfo2Provider(json);
                    case "expo3":
                        return new ExpoInfo3Provider(json);
                    case "expo4":
                        return new ExpoInfo4Provider(json);
                    case "expo5":
                        return new ExpoInfo5Provider(json);
                    case "expo6":
                        return new ExpoInfo6Provider(json);
                    case "expo7":
                        return new ExpoInfo7Provider(json);
                    case "expo8":
                        return new ExpoInfo8Provider(json);
                    case "expo9":
                        return new ExpoInfo9Provider(json);
                    case "expo10":
                        return new ExpoInfo10Provider(json);
                    case "company":
                        return new CompanyProvider(json);
                    case "company1":
                        return new Company1Provider(json);
                    case "person":
                        return new PersonProvider(json);
                    case "reward":
                        return new RewardProvider(json);
                    case "rewardlist":
                        return new RewardListProvider(json);
                    case "forum":
                        return new ForumProvider(json);
                    case "forum1":
                        return new Forum1Provider(json);
                    case "magazine":
                        return new MagazineProvider(json);
                    case "magazine1":
                        return new Magazine1Provider(json);


                    case "news":
                        return new NewsProvider(json);

                    case "newsdetail":
                        return new NewsDetailProvider(json);

                    case "weibo":
                        return new WeiboProvider(json);

                    case "advertise":
                        return new AdvertiseProvider(json);

                    #endregion
                }

                msgType = MessageCodeType.InvalidCommandType;
            }
            catch (Exception ex)
            {
                msgType = MessageCodeType.ConvertFromJsonError;
                LogEvent.LogError("CreateProvider失败, 参数json=" + json , ex);
            }

            return null;
        }
        
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        
    }
}